package com.cs.mq;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import com.cs.mq.util.Base64;
import com.ibm.mq.MQC;
import com.ibm.mq.MQException;
import com.ibm.mq.MQGetMessageOptions;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;
import com.ibm.mq.constants.CMQC;

/**
 * @author Sam.Lee
 * @version Created：Feb 27, 2013 5:08:11 PM
 */
public class GetMQMessage {
	public static void main(String[] args) throws Exception {
		List<Object> messageList = new ArrayList<Object>();
		MQQueueManager queueManager = null;
		MQQueue mqQueue = null;
		String pstrCorrelationID = null;
		boolean isAutoCommit = false;
		try {
			Hashtable<String, Object> properties = new Hashtable<String, Object>();
			properties.put("hostname", "localhost");
			properties.put("port", 1414);
			properties.put("channel", "ESP");
			// IBM Coded Character Set Identifiers (CCSID)
			properties.put("CCSID", 1381);
			properties.put("userID", "administrator");
			properties.put("password", "942249");
			queueManager = new MQQueueManager("MQHA", properties);
			mqQueue = queueManager.accessQueue("EETOESP", MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_OUTPUT | MQC.MQOO_INQUIRE, null, null, null);
			String[] arrMessage = null;
			MQMessage rcvMessage = null;
			for (int i = 0; i < mqQueue.getCurrentDepth(); i++) {
				arrMessage = new String[4];
				rcvMessage = new MQMessage();
				MQGetMessageOptions gmo = new MQGetMessageOptions();
				if (!isAutoCommit) {
					gmo.options = gmo.options + CMQC.MQGMO_SYNCPOINT;
				}
				if (pstrCorrelationID != null) {
					rcvMessage.correlationId = Base64.base64ToByteArray(pstrCorrelationID);
				}
				MQException.log = null;
				mqQueue.get(rcvMessage, gmo);
				int len = rcvMessage.getDataLength();
				byte[] buf = new byte[len];
				rcvMessage.readFully(buf, 0, len);
				String lstrMessage = new String(buf);
				String lstrMessageID = Base64
						.byteArrayToBase64(rcvMessage.messageId);
				String lstrFeedback = String.valueOf(rcvMessage.feedback);
				String lstrCorrelationID = Base64
						.byteArrayToBase64(rcvMessage.correlationId);
				arrMessage[0] = lstrMessageID;
				arrMessage[1] = lstrMessage;
				arrMessage[2] = lstrFeedback;
				arrMessage[3] = lstrCorrelationID;
				messageList.add(arrMessage);
				System.out.println(arrMessage[1]);
			}
		} catch (MQException e) {
			if (mqQueue != null) {
				mqQueue.close();
			}
			if (queueManager != null) {
				queueManager.disconnect();
			}
			if (e.reasonCode == 2033) {
				messageList.add(new String[4]);
			} else {
				throw e;
			}
		} finally {
			if (isAutoCommit) {
				if (mqQueue != null) {
					mqQueue.close();
				}
				if (queueManager != null) {
					queueManager.disconnect();
				}
			}
		}
		// return messageList;
	}
}
